package com.ruoyi.system.config;

import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

//@Service
@Slf4j
public class InitDataService {
        @Autowired
        private SysConfigMapper sysConfigMapper;

        private final Map<String, Object> configCache = new ConcurrentHashMap<>();
        private final AtomicBoolean loaded = new AtomicBoolean(false);

        @PostConstruct
        public synchronized void init() {
            if (!loaded.get()) {
                loadAllConfigs();
                loaded.set(true);
            }
        }

        private void loadAllConfigs() {
            try {
                List<SysConfig> sysConfigs = sysConfigMapper.selectList(null);
                configCache.clear();

                for (SysConfig config : sysConfigs) {
                    configCache.put(config.getConfigKey(), config);
                }

                log.info("成功加载 {} 条配置信息", configCache.size());
            } catch (Exception e) {
                log.error("加载配置数据失败", e);
            }
        }

        public Object getConfig(String key) {
            if (!loaded.get()) {
                init();
            }
            if (configCache.get(key) == null){
                reload();
            }
            return configCache.get(key);
        }

        // 重新加载配置（可用于手动刷新）
        public void reload() {
            loadAllConfigs();
        }

        // 获取所有配置
        public Map<String, Object> getAllConfigs() {
            return new HashMap<>(configCache);
        }

}
